package com.woniuxy.portal.commodity.controller;


import com.woniuxy.health.model.commodity.Goods;
import com.woniuxy.portal.commodity.dto.IpAddrDTO;
import com.woniuxy.portal.commodity.dto.WeatherDTO;
import com.woniuxy.portal.commodity.service.IGoodsService;
import com.woniuxy.utils.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author woniuxy
 * @since 2023-09-04
 */
@RestController
@RequestMapping("/goods")
public class GoodsController {

    private final IGoodsService goodsServiceImpl;
    private final RestTemplate restTemplate;

    static String key = "e06fd62be50192fbe10d24d0fc6c3ed9";

    @Autowired
    public GoodsController(IGoodsService goodsServiceImpl, RestTemplate restTemplate) {
        this.goodsServiceImpl = goodsServiceImpl;
        this.restTemplate = restTemplate;
    }

    // 根据ip地址查询用户定位，根据用户定位查询当地天气，并查询对应商品返回推荐
    @GetMapping("/getByWeather")
    public Result getByWeather(String ip) {

        // 通过ip地址查询用户定位
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        String url = "https://restapi.amap.com/v3/ip?key=" + key + "&ip=" + ip;

        HttpMethod method = HttpMethod.GET;

        HttpEntity entity = new HttpEntity(headers);
        ResponseEntity<IpAddrDTO> re =
                restTemplate.exchange(url, method, entity, IpAddrDTO.class);
        IpAddrDTO body = re.getBody();

        // 通过定位，查询当地天气情况
        url = "https://restapi.amap.com/v3/weather/weatherInfo?key=" + key + "&city=" + body.getAdcode();

        ResponseEntity<WeatherDTO> weatherInfo
                = restTemplate.exchange(url, method, entity, WeatherDTO.class);

        WeatherDTO body1 = weatherInfo.getBody();
        String weather = body1.getLives().get(0).getWeather();

        List<Goods> list = goodsServiceImpl.getByWeather(weather);
        return Result.ok(list);
    }







}
